package cn.edu.scnu.semart.order.controller;

import cn.edu.scnu.semart.common.utils.UserContext;
import cn.edu.scnu.semart.model.order.Order;
import cn.edu.scnu.semart.model.order.OrderDTO;
import cn.edu.scnu.semart.model.order.OrderRequest;
import cn.edu.scnu.semart.model.order.OrderStatistics;
import cn.edu.scnu.semart.order.service.OrderService;
import cn.edu.scnu.semart.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
@Api(tags = "订单管理")
public class OrderController {
    private final OrderService orderService;

    @PostMapping
    public Map<String, Object> createOrder(@RequestBody OrderRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用服务层创建订单
            OrderDTO order = orderService.createOrder(request.getUserId(), request.getAddressId());

            // 获取订单总价（转换为元）
            BigDecimal totalPrice = order.getTotalPrice();

            // 生成支付URL
            String paymentUrl = String.format(
                    "/payment/pay?price=%s&subject=%s&outTradeNo=%s",
                    totalPrice.toString(),
                    URLEncoder.encode("订单支付：" + order.getOrderNumber(), "UTF-8"),
                    order.getPayTradeNo() // 这里用 payTradeNo 字段
            );

            result.put("success", true);
            result.put("data", order);
            result.put("paymentUrl", paymentUrl);
        } catch (Exception e) {
            // 特殊处理 JSON 解析错误
            if (e.getCause() instanceof HttpMessageNotReadableException) {
                handleJsonParseError(result, e);
            } else {
                result.put("success", false);
                result.put("message", e.getMessage());
            }
        }
        return result;
    }

    @PostMapping("/repay/{orderId}")
    @ResponseBody
    public Map<String, Object> repay(@PathVariable Integer orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 1. 查原订单
            Order order = orderService.getById(orderId);
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }

            // 2. 只允许“待支付”的订单重新支付
            List<String> allowStatus = Arrays.asList("pending_payment");
            if (!allowStatus.contains(order.getStatus())) {
                result.put("success", false);
                result.put("message", "当前订单状态不允许重新支付");
                return result;
            }
            // 3. 生成新的商户订单号
            String newOutTradeNo = order.getOrderNumber() + "_R" + System.currentTimeMillis();
            // 4. 只更新payTradeNo字段
            order.setPayTradeNo(newOutTradeNo);
            order.setStatus("pending_payment");
            orderService.updateById(order);
            // 5. 返回新的支付链接
            String paymentUrl = "/payment/pay?price=" + order.getTotalPrice() +
                    "&subject=" + URLEncoder.encode("订单重新支付：" + newOutTradeNo, "UTF-8") +
                    "&outTradeNo=" + newOutTradeNo;

            result.put("success", true);
            result.put("paymentUrl", paymentUrl);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    // 处理 JSON 解析错误
    private void handleJsonParseError(Map<String, Object> result, Exception e) {
        result.put("success", false);
        result.put("message", "服务响应格式错误");

        // 添加详细的错误信息
        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("errorType", "JSON_PARSE_ERROR");
        errorDetails.put("originalMessage", e.getMessage());

        // 提取更具体的错误信息
        if (e.getCause() != null) {
            Throwable cause = e.getCause();
            if (cause instanceof MismatchedInputException) {
                MismatchedInputException mie = (MismatchedInputException) cause;
                errorDetails.put("targetType", mie.getTargetType().getSimpleName());
                errorDetails.put("location", String.format("Line %d, Column %d",
                        mie.getLocation().getLineNr(),
                        mie.getLocation().getColumnNr()));
            }
        }

        result.put("errorDetails", errorDetails);
    }

    //获取订单详情
    @GetMapping("/{orderId}")
    public Map<String, Object> getOrder(@PathVariable Integer orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            OrderDTO order = orderService.getOrderDetails(orderId);
            result.put("success", true);
            result.put("data", order);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    //获取用户订单列表
    @PutMapping("/user/{userId}")
    public Map<String, Object> getUserOrders(@PathVariable Integer userId,@RequestParam(value = "status", required = false) String status) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<OrderDTO> orders = orderService.getUserOrders(userId,status);
            result.put("success", true);
            result.put("data", orders);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 管理员后台-获取订单分页列表
     */
    @ApiOperation(value = "获取订单分页列表")
    @GetMapping("/admin/{page}/{limit}")
    public Map<String, Object> getOrderList(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,

            @ApiParam(name = "orderQueryVo", value = "查询对象", required = false)
            OrderQueryVo orderQueryVo) {
        Map<String, Object> result = new HashMap<>();

        try {
            if (orderQueryVo == null) {
                orderQueryVo = new OrderQueryVo();
            }
            Page<Order> pageParam = new Page<>(page, limit);
            IPage<OrderDTO> pageModel = orderService.selectPage(pageParam, orderQueryVo);

            result.put("success", true);
            result.put("data", pageModel);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        return result;
    }

    /**
     * 更新订单状态
     */
    @ApiOperation(value = "更新订单状态")
    @PutMapping("/status/{id}/{status}")
    public Map<String, Object> updateStatus(
            @PathVariable Integer id,
            @PathVariable String status) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 更新订单状态
            orderService.updateOrderStatus(id, status);

            result.put("success", true);
            result.put("message", "订单状态更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

/*    @GetMapping("/statistics")
    public Map<String, Object> getStatistics(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date start,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date end,
            @RequestParam(defaultValue = "daily") String granularity) {

        Map<String, Object> result = new HashMap<>();
        try {
            OrderStatistics stats = orderService.getOrderStatistics(start, end, granularity);
            result.put("success", true);
            result.put("data", stats);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }*/
}
